package cn.iocoder.an.module.business.utils;

import lombok.Data;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class WeComRobotUtil {

    private final RestTemplate restTemplate;


    public WeComRobotUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public boolean send(String webhookUrl, WeComMessage message) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<WeComMessage> entity = new HttpEntity<>(message, headers);

            ResponseEntity<WeComResponse> response = restTemplate.postForEntity(webhookUrl, entity, WeComResponse.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return "0".equals(response.getBody().getErrcode());
            }
        } catch (Exception e) {
            System.err.println("发送企业微信群消息失败: " + e.getMessage());
        }
        return false;
    }

    // 使用 Lombok 简化响应类
    @Data
    public static class WeComResponse {
        private String errcode;
        private String errmsg;
    }
}